package com.tnsw.facebookautoliker.database;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;

import com.tnsw.coreutils.MyLog;
import com.tnsw.coreutils.database.DBManagerBase;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.format.DateFormat;
import android.util.Log;

public class DBManager extends DBManagerBase {

	private static boolean sIsRunning = false;
	private static DBManager sInstance;
	
	public static DBManager getInstance(Context context) {
		if (sIsRunning == false) {
			sInstance = new DBManager(context);
		}
		
		return(sInstance);
	}
	
	public DBManager(Context context) {
		super(context);
		this.tag = "DBManager";
		
		sIsRunning = true;
		sInstance = this;
	}
	
	public void testReflection() {
		try {
			Class c = Class.forName("com.tnsw.facebookautoliker.database.FriendsList");	
			Object o = c.getConstructors()[0].newInstance(null);
			MyLog.d(tag, "type=" + o.getClass().getName());
			
			Field id = c.getDeclaredField("id");
			id.set(o, "10xx");
			
			FriendsList fl = (FriendsList) o;
			MyLog.d(tag, "id=" + fl.id);
			
		} catch (Exception e) {
			MyLog.e(tag, "testReflection - " + e.toString(), e);
		}
		

	}
	
	
	public void updateFriendsListById(FriendsList fl) {
		SQLiteDatabase db = null;
		
		try {
			db = this.getWritableDatabase();
			String sql = "select * from friends_list where id=?";
			Cursor cursor = db.rawQuery(sql, new String[] {fl.id});
			int nameIdx = cursor.getColumnIndex("name");
			int photoPathIdx = cursor.getColumnIndex("photo_path");
			int createdIdx  = cursor.getColumnIndex("created");
		
			cursor.moveToFirst();
			if (!cursor.isAfterLast()) {
				// Has existing id in 'friends_list' table
			
			} else {
				// do insert new record
				ContentValues values = new ContentValues();
				int primarykey = super.getNewPrimarykey();
				
				fl.primarykey = primarykey;
				/*
				values.put("primarykey", primarykey);
				values.put("id", fl.id);
				values.put("name", fl.name);
				values.put("photo_path", fl.photo_path);
								
				Calendar c = Calendar.getInstance();
				c.setTimeInMillis(System.currentTimeMillis());
				long now = System.currentTimeMillis();
				
				values.put("created", now);
						
				long insertId = db.insert("friends_list", null, values);
				Log.d(tag, "inserted new friends_list");
				*/
				long rowId = this.insertRecord("friends_list", fl, "photo_path", true);
				MyLog.d(tag, "inserted rowId=" + rowId);
			}
			
		} catch (Exception e) {
			MyLog.e(tag, "updateFriendsList() - " + e.toString(), e);
		}
		
		if (db != null) {
			db.close();
		}
		
	}

}
